package com.talkyun.utils.crypt;

import com.talkyun.utils.AesCipher;
import com.talkyun.utils.codec.Base32;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

import static javax.crypto.Cipher.DECRYPT_MODE;
import static javax.crypto.Cipher.ENCRYPT_MODE;

public class RsaCrypt {
    public static final String CHARSET = "UTF-8";
    public static final String RSA_ALGORITHM = "RSA";

    public static Map<String, String> createKeyPair(int keySize) {
        KeyPairGenerator kpg;
        try {
            kpg = KeyPairGenerator.getInstance(RSA_ALGORITHM);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalArgumentException("No such algorithm  " + RSA_ALGORITHM);
        }

        kpg.initialize(keySize);
        KeyPair keyPair = kpg.generateKeyPair();

        Key publicKey = keyPair.getPublic();
        String publicKeyStr = Base64.getEncoder().encodeToString(publicKey.getEncoded());

        Key privateKey = keyPair.getPrivate();
        String privateKeyStr = Base64.getEncoder().encodeToString(privateKey.getEncoded());

        Map<String, String> keyPairMap = new HashMap<>();
        keyPairMap.put("publicKey", publicKeyStr);
        keyPairMap.put("privateKey", privateKeyStr);
        return keyPairMap;
    }

    public static RSAPublicKey getPublicKey(String publicKey) {
        // 通过X509编码的Key指令获得公钥对象
        try {
            KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKey));
            return (RSAPublicKey) keyFactory.generatePublic(x509KeySpec);
        } catch (GeneralSecurityException e) {
            throw new RuntimeException(e);
        }
    }

    public static RSAPrivateKey getPrivateKey(String privateKey) {
        // 通过PKCS#8编码的Key指令获得私钥对象
        try {
            KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey));
            return (RSAPrivateKey) keyFactory.generatePrivate(pkcs8KeySpec);
        } catch (GeneralSecurityException e) {
            throw new RuntimeException(e);
        }
    }

    public static String encryptByPublicKey(String data, String publicKey) {
        return encryptByPublicKey(data, RsaCrypt.getPublicKey(publicKey));
    }

    public static String encryptToBase32ByPublicKey(String data, String publicKey) {
        return Base32.encode(doEncryptByPublicKey(data, RsaCrypt.getPublicKey(publicKey)));
    }

    public static String encryptByPublicKey(String data, RSAPublicKey publicKey) {
        return Base64.getEncoder().encodeToString(doEncryptByPublicKey(data, publicKey));
    }

    private static byte[] doEncryptByPublicKey(String data, RSAPublicKey publicKey) {
        try {
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(ENCRYPT_MODE, publicKey);
            return rsaSplitCodec(cipher, ENCRYPT_MODE, data.getBytes(CHARSET), publicKey.getModulus().bitLength());
        } catch (Exception e) {
            throw new RuntimeException("RSA加密字符串异常!", e);
        }
    }

    public static String decryptByPublicKey(String data, String publicKey) {
        return decryptByPublicKey(data, getPublicKey(publicKey));
    }

    public static String decryptFromBase32ByPublicKey(String data, String publicKey) {

        return decryptByPublicKey(data, getPublicKey(publicKey));
    }

    public static String decryptByPublicKey(String data, RSAPublicKey publicKey) {
        try {
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(DECRYPT_MODE, publicKey);
            return new String(rsaSplitCodec(cipher, DECRYPT_MODE, Base64.getDecoder().decode(data), publicKey.getModulus().bitLength()), CHARSET);
        } catch (Exception e) {
            throw new RuntimeException("RSA解密字符串异常!", e);
        }
    }

    public static String encryptByPrivateKey(String data, String privateKey) {
        return encryptByPrivateKey(data, getPrivateKey(privateKey));
    }

    public static String encryptByPrivateKey(String data, RSAPrivateKey privateKey) {
        try {
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            // 每个Cipher初始化方法使用一个模式参数opmod，并用此模式初始化Cipher对象。此外还有其他参数，包括密钥key、包含密钥的证书certificate、算法参数params和随机源random。
            cipher.init(ENCRYPT_MODE, privateKey);
            return Base64.getEncoder().encodeToString(rsaSplitCodec(cipher, ENCRYPT_MODE, data.getBytes(CHARSET), privateKey.getModulus().bitLength()));
        } catch (Exception e) {
            throw new RuntimeException("RSA加密字符串异常!", e);
        }
    }

    public static String decryptByPrivateKey(String data, String privateKey) {
        return decryptByPrivateKey(data, getPrivateKey(privateKey));
    }

    public static String decryptByPrivateKey(String data, RSAPrivateKey privateKey) {
        try {
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(DECRYPT_MODE, privateKey);
            return new String(rsaSplitCodec(cipher, DECRYPT_MODE, Base64.getDecoder().decode(data), privateKey.getModulus().bitLength()), CHARSET);
        } catch (Exception e) {
            throw new RuntimeException("RSA解密字符串异常!", e);
        }
    }


    // rsa切割解码 , ENCRYPT_MODE, 加密数据,DECRYPT_MODE,解密数据
    private static byte[] rsaSplitCodec(Cipher cipher, int opmode, byte[] datas, int keySize) {
        int maxBlock = 0;  // 最大块
        if (opmode == DECRYPT_MODE) {
            maxBlock = keySize / 8;
        } else {
            maxBlock = keySize / 8 - 11;
        }

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0, i = 0;
        byte[] buff;
        try {
            while (datas.length > offSet) {
                if (datas.length - offSet > maxBlock) {
                    // 可以调用以下的doFinal（）方法完成加密或解密数据：
                    buff = cipher.doFinal(datas, offSet, maxBlock);
                } else {
                    buff = cipher.doFinal(datas, offSet, datas.length - offSet);
                }
                out.write(buff, 0, buff.length);
                i++;
                offSet = i * maxBlock;
            }
        } catch (Exception e) {
            throw new RuntimeException("RSA加解密阀值为(" + maxBlock + ")时发生异常!", e);
        }

        return out.toByteArray();
    }

    public static void main(String[] args) throws Exception {
        Map<String, String> keyMap = RsaCrypt.createKeyPair(4096);

        String publicKey = keyMap.get("publicKey");
        String privateKey = keyMap.get("privateKey");

        publicKey = AesCipher.get().encrypt(publicKey);
        privateKey = AesCipher.get().encrypt(privateKey);

        System.out.println("公钥: " + publicKey.length() + "\n\r" + publicKey);
        System.out.println("私钥：" + privateKey.length() + "\n\r" + privateKey);

        //        System.out.println("\n\n公钥加密 => 私钥解密");
        //        String src = "大汉将军，法力无边！大汉将军，法力无边！! GOD ...";
        //        System.out.println("\r明文：" + src);
        //        System.out.println("\r大小：" + src.getBytes().length);
        //
        //        String encodedData = RsaCrypt.encryptByPublicKey(src, RsaCrypt.getPublicKey(publicKey));  // 传入明文和公钥加密,得到密文
        //        System.out.println("密文：" + encodedData);
        //        System.out.println("\r大小：" + encodedData.getBytes().length);
        //
        //        String decodedData = RsaCrypt.decryptByPrivateKey(encodedData, RsaCrypt.getPrivateKey(privateKey)); // 传入密文和私钥,得到明文
        //        System.out.println("解密: " + decodedData);
        //
        //        System.out.println(decodedData.equals(src));
        //
        //        String privateCryptData = RsaCrypt.encryptByPrivateKey(src, RsaCrypt.getPrivateKey(privateKey));
        //        System.out.println(privateCryptData);
        //        String publicDecryptData = RsaCrypt.decryptByPublicKey(privateCryptData, RsaCrypt.getPublicKey(publicKey));
        //        System.out.println(publicDecryptData);
        //        System.out.println(publicDecryptData.equals(src));
        //
        //        String bigSrcData = "xxx"; // getRandomString(30 * 1024 * 1024);
        //
        //        System.out.println("...");
        //        long time = System.currentTimeMillis();
        //        // RsaCrypt.encryptByPublicKey(bigSrcData, RsaCrypt.getPublicKey(publicKey));
        //        AesCipher.get().encrypt(bigSrcData);
        //        System.out.println(System.currentTimeMillis() - time);
    }

}

